import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {Navbar} from 'ionic-angular';

/**
 * Generated class for the DatePickerPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-date-picker',
  templateUrl: 'date-picker.html',
})
export class DatePickerPage {
  //用于监听返回事件
  @ViewChild(Navbar) navBar: Navbar;
  //今天
  today = {year: 0, month: 0, day: 0, week: 0};
  //今年
  todayYear = 0;
  //加载完成
  didLoad = false;
  //周定义
  week = [
    {name: '日', color: '#ff902d'},
    {name: '一', color: 'black'},
    {name: '二', color: 'black'},
    {name: '三', color: 'black'},
    {name: '四', color: 'black'},
    {name: '五', color: 'black'},
    {name: '六', color: '#ff902d'},
  ];
  //月定义
  month = [
    {name: '1月', value: 1},
    {name: '2月', value: 2},
    {name: '3月', value: 3},
    {name: '4月', value: 4},
    {name: '5月', value: 5},
    {name: '6月', value: 6},
    {name: '7月', value: 7},
    {name: '8月', value: 8},
    {name: '9月', value: 9},
    {name: '10月', value: 10},
    {name: '11月', value: 11},
    {name: '12月', value: 12},
  ];
  days = [];
  /**
   * 年份选择数据格式
   */
  private yearRange = {startYear: 1996, endYear: 1996, defaultYear: 1996};
  //显示年份选择
  private showYearSelect = false;
  //回调
  private callBack: any;
  //选择类型
  private type: any;
  //点击次数
  private tabbedTimes = 0;
  //起始日期元素
  private startElement: any;
  //结束日期元素
  private endElement: any;
  //颜色
  private colors = {
    blue: '#66ccff',
    deepBlue: '#06a2d0'
  };
  //起止时间以及几晚
  private startToEnd = {
    start: {year: 0, month: 0, day: ''},
    end: {year: 0, month: 0, day: ''},
    evenings: 0
  };

  constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController, public ref: ChangeDetectorRef) {
    this.callBack = this.navParams.get("callback");
    this.type = this.navParams.get("type");
    this.initDate();
  }

  initDate() {
    let myDate = new Date();
    this.todayYear = myDate.getFullYear();
    this.today.year = myDate.getFullYear();
    this.today.day = myDate.getDate();
    this.today.month = (myDate.getMonth() + 1);
    this.today.week = myDate.getDay();
  }

  init() {
    this.days = [];
    for (let item of this.month) {
      let dayCount = this.getDays(this.today.year, item.value);
      let temp = {days: []};
      let weekTemp = new Date(this.today.year, item.value - 1, 1).getDay();
      for (let i = 0; i < weekTemp; i++) {
        temp.days.push({name: '', price: ''});
      }

      for (let i = 0; i < dayCount; i++) {
        temp.days.push({name: (i + 1).toString(), price: '', disable: false});
      }
      this.days.push(temp);
    }
    console.log(this.days);

  }

  ionViewDidLoad() {
    switch (this.type) {
      //单日期选择
      case 'singleDate':
        this.init();
        break;
      //带年份的日期选择
      case 'singleDate|yearRange':
        let temp = this.navParams.get('range');
        if (temp && temp.startYear && temp.endYear && temp.defaultYear) {
          this.yearRange = temp;
          this.today.year = temp.defaultYear;
          this.showYearSelect = true;
        }
        this.init();
        break;
      //住店日期选择
      case 'hotel':
        this.init();
        break;
      case 'range':
        this.init();
        break;
      case 'hotelCalender':
        this.init();
        break;
    }
    this.didLoad = true;
    this.setBackButtonAction();
    // this.showToday();
  }

  private getDays(year, month) {
    let d = new Date(year, month, 0);
    return d.getDate();
  }

  chooseDate(year, month, day, id) {
    if (day.name && day.name.trim() !== '') {
      let element = document.getElementById(id);
      switch (this.type) {
        case 'hotel':
          this.tabbedTimes++;
          if (this.tabbedTimes === 1) {
            this.setColor(element, this.colors.deepBlue);
            this.startElement = element;
            this.setText(this.startElement.children[2], '入住');
            this.startToEnd.start.year = year;
            this.startToEnd.start.day = day.name;
            this.startToEnd.start.month = month;
            console.log(this.startToEnd);
          }
          else if (this.tabbedTimes === 2) {
            if (this.startToEnd.start.year <= year && this.startToEnd.start.month <= month) {
              if (this.startToEnd.start.month === month && parseInt(this.startToEnd.start.day) < parseInt(day.name)) {
                this.setColor(element, this.colors.deepBlue);
                this.endElement = element;
                this.setText(this.endElement.children[2], '离店');
                this.startToEnd.end.year = year;
                this.startToEnd.end.day = day.name;
                this.startToEnd.end.month = month;
                console.log(this.startToEnd);
                this.presentConfirm();
              }
              else if (this.startToEnd.start.month < month) {
                this.setColor(element, this.colors.deepBlue);
                this.endElement = element;
                this.setText(this.endElement.children[2], '离店');
                this.startToEnd.end.year = year;
                this.startToEnd.end.day = day.name;
                this.startToEnd.end.month = month;
                console.log(this.startToEnd);
                this.presentConfirm();

              }
              else {
                this.reset();
                this.setColor(element, this.colors.deepBlue);
                this.startElement = element;
                this.setText(this.startElement.children[2], '入住');
                this.startToEnd.start.year = year;
                this.startToEnd.start.day = day.name;
                this.startToEnd.start.month = month;
                console.log(this.startToEnd);
                this.tabbedTimes = 1;
              }

            }
            else {
              this.reset();
              this.setColor(element, this.colors.deepBlue);
              this.startElement = element;
              this.setText(this.startElement.children[2], '入住');
              this.startToEnd.start.year = year;
              this.startToEnd.start.day = day.name;
              this.startToEnd.start.month = month;
              console.log(this.startToEnd);
              this.tabbedTimes = 1;
            }

          }
          else if (this.tabbedTimes >= 3) {
            this.reset();
            this.setColor(element, this.colors.deepBlue);
            this.startElement = element;
            this.setText(this.startElement.children[2], '入住');
            this.startToEnd.start.year = year;
            this.startToEnd.start.day = day.name;
            this.startToEnd.start.month = month;
            console.log(this.startToEnd);
            this.tabbedTimes = 1;
          }

          break;
        case 'range':
          this.tabbedTimes++;
          if (this.tabbedTimes === 1) {
            this.setColor(element, this.colors.deepBlue);
            this.startElement = element;
            this.setText(this.startElement.children[2], '开始');
            this.startToEnd.start.year = year;
            this.startToEnd.start.day = day.name;
            this.startToEnd.start.month = month;
            console.log(this.startToEnd);
          }
          else if (this.tabbedTimes === 2) {
            if (this.startToEnd.start.year <= year && this.startToEnd.start.month <= month) {
              if (this.startToEnd.start.month === month && parseInt(this.startToEnd.start.day) < parseInt(day.name)) {
                this.setColor(element, this.colors.deepBlue);
                this.endElement = element;
                this.setText(this.endElement.children[2], '结束');
                this.startToEnd.end.year = year;
                this.startToEnd.end.day = day.name;
                this.startToEnd.end.month = month;
                console.log(this.startToEnd);
                this.presentConfirm();
              }
              else if (this.startToEnd.start.month < month) {
                this.setColor(element, this.colors.deepBlue);
                this.endElement = element;
                this.setText(this.endElement.children[2], '结束');
                this.startToEnd.end.year = year;
                this.startToEnd.end.day = day.name;
                this.startToEnd.end.month = month;
                console.log(this.startToEnd);
                this.presentConfirm();

              }
              else {
                this.reset();
                this.setColor(element, this.colors.deepBlue);
                this.startElement = element;
                this.setText(this.startElement.children[2], '开始');
                this.startToEnd.start.year = year;
                this.startToEnd.start.day = day.name;
                this.startToEnd.start.month = month;
                console.log(this.startToEnd);
                this.tabbedTimes = 1;
              }

            }
            else {
              this.reset();
              this.setColor(element, this.colors.deepBlue);
              this.startElement = element;
              this.setText(this.startElement.children[2], '开始');
              this.startToEnd.start.year = year;
              this.startToEnd.start.day = day.name;
              this.startToEnd.start.month = month;
              console.log(this.startToEnd);
              this.tabbedTimes = 1;
            }

          }
          else if (this.tabbedTimes >= 3) {
            this.reset();
            this.setColor(element, this.colors.deepBlue);
            this.startElement = element;
            this.setText(this.startElement.children[2], '开始');
            this.startToEnd.start.year = year;
            this.startToEnd.start.day = day.name;
            this.startToEnd.start.month = month;
            console.log(this.startToEnd);
            this.tabbedTimes = 1;
          }
          break;
        case 'hotelCalender':
          break;
        default:
          this.setColor(element, this.colors.blue);
          this.callBack({year: year, month: month, day: day.name}).then(() => {
            this.navCtrl.pop();
          });
          break;
      }
    }
  }

  setColor(element, color) {
    element.style = 'color:white;background:' + color + ';';
  }

  setText(element, text) {
    element.innerText = text;
  }

  setBackButtonAction() {
    this.navBar.backButtonClick = () => {
      this.callBack({}).then(() => {
        this.navCtrl.pop()
      });
    };

  }

  showRadio() {
    let alert = this.alertCtrl.create();
    alert.setTitle('年份选择');
    for (let i = this.yearRange.startYear; i <= this.yearRange.endYear; i++) {
      alert.addInput({
        type: 'radio',
        label: i + '年',
        value: i.toString(),
        // checked: true
      });
    }

    alert.addButton('取消');
    alert.addButton({
      text: '确认',
      handler: data => {
        this.today.year = data;
        this.init();
        this.ref.markForCheck();
        this.ref.detectChanges();
        this.showToday();
      }
    });
    alert.present();
  }

  showToday() {
    if (this.today.year == this.todayYear)
      document.getElementById(this.today.year + '|' + this.today.month + '|' + this.today.day).innerHTML = '今天';
  }

  presentConfirm() {
    let alert = this.alertCtrl.create({
      title: '确认时间',
      message: this.startToEnd.start.month + '月' + this.startToEnd.start.day + '日' + ' 至 ' + this.startToEnd.end.month + '月' + this.startToEnd.end.day + '日',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
          }
        },
        {
          text: '确认',
          handler: () => {
            this.callBack({
              start: {
                year: this.startToEnd.start.year,
                month: this.startToEnd.start.month,
                day: this.startToEnd.start.day
              },
              end: {year: this.startToEnd.end.year, month: this.startToEnd.end.month, day: this.startToEnd.end.day}
            }).then(() => {
            });
            this.navCtrl.pop();
          }
        }
      ]
    });
    alert.present();
  }

  reset() {
    this.startElement.style = 'color:black;background:white;';
    if (this.endElement) {
      this.endElement.style = 'color:black;background:white;';
      this.endElement.children[2].innerText = '';
    }
    this.startElement.children[2].innerText = '';
  }

}

